<template>
  <view class="index-content">
    <view class="logo">
      <image mode="widthFix" src="@/static/images/logo.png"></image>
    </view>
    <view class="device-list">
      <view class="device-item">
        <view class="item-left">
          <view class="label">设备名称：</view>
          <view class="content">
            {{
              batteryData.connected
                ? batteryData.bluetoothName
                  ? batteryData.bluetoothName
                  : batteryData.deviceName
                : '--'
            }}
          </view>
        </view>
        <view class="item-right">
          <view class="item-btn" @click="searchDevices">设备列表</view>
        </view>
      </view>
      <view class="device-item">
        <view class="item-left">
          <view class="label">软件版本：</view>
          <view class="content">
            {{ batteryData.connected ? batteryData.softwareVersion : '--' }}
          </view>
        </view>
        <view class="item-right"></view>
      </view>
      <view class="device-item">
        <view class="item-left">
          <view class="label">硬件版本：</view>
          <view class="content">
            {{ batteryData.connected ? batteryData.hardwareVersion : '--' }}
          </view>
        </view>
        <view class="item-right">
          <view class="item-btn" @click="startOat">OTA升级</view>
        </view>
      </view>
    </view>
    <view class="wendu-box">
      <view class="device-wendu">
        <view class="icon">
          <image src="../../static/images/wendu.png" mode=""></image>
          {{ batteryData.connected ? batteryData.temperature + 'C°' : '--' }}
        </view>
      </view>
    </view>
    <view class="device-rule-box">
      <view class="device-rule-top">
        <image src="../../static/images/rule_3.png" mode=""></image>
      </view>
      <view class="rule-item">
        <view class="item-master" style="width: 100%">
          <view class="top">
            <view>
              <image
                style="width: 80rpx; height: 70rpx"
                src="../../static/images/mabiao.png"
                mode=""></image>
            </view>
            <view class="title">
              {{ batteryData.connected ? batteryData.voltage + 'V' : '--' }}
            </view>
          </view>
          <view class="rule-img">
            <image src="../../static/images/rule_1.png" mode="widthFix"></image>
          </view>
        </view>
      </view>
      <view class="rule-item">
        <view class="item-master" style="width: 100%">
          <view class="top">
            <view>
              <image
                style="width: 45rpx; height: 80rpx"
                src="../../static/images/dianchi.png"
                mode=""></image>
            </view>
            <view class="title">
              {{ batteryData.connected ? batteryData.batteryPercentage + '%' : '--' }}
            </view>
          </view>
          <view class="rule-img">
            <image src="../../static/images/rule_1.png" mode="widthFix"></image>
          </view>
        </view>
      </view>

      <view class="rule-item">
        <view class="item-master" style="width: 100%">
          <view class="top">
            <view>
              <image
                style="width: 72rpx; height: 72rpx"
                src="../../static/images/speed.png"
                mode=""></image>
            </view>
            <view class="title">
              {{ batteryData.connected ? batteryData.range + 'km' : '--' }}
            </view>
          </view>
          <view class="rule-img">
            <image src="../../static/images/rule_2.png" mode="widthFix"></image>
          </view>
        </view>
        <view class="item-btn" @click="inputOpen('续航校准')">续航校准</view>
      </view>
    </view>
    <view class="device-event">
      <view class="event-item" style="width: 100%" @click="selectOpen('数据源')">
        <view class="left">
          <view class="title">{{ batteryData.connected ? sourceName : '--' }}</view>
          <view class="label">数据源</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 100%" @click="selectOpen('车型选择')">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.vehicleTypeName : '--' }}
          </view>
          <view class="label">车型选择</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>

      <view class="event-item" style="width: 286rpx" @click="inputOpen('电池串数')">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.packBatteryCount : '--' }}
          </view>
          <view class="label">串数</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 286rpx" @click="inputOpen('电耗')">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.consumption : '--' }}
          </view>
          <view class="label">电耗</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 286rpx" @click="inputOpen('容量')">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.batteryCapacity : '--' }}
          </view>
          <view class="label">容量</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 286rpx" @click="selectOpen('电池类型')">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.batteryTypeName : '--' }}
          </view>
          <view class="label">电池类型</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 100%" @click="inputOpen('蓝牙名称')">
        <view class="left">
          <view class="title">{{ batteryData.connected ? batteryData.bluetoothName : '--' }}</view>
          <view class="label">蓝牙名称</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 426rpx" @click="handleProtectBluetooth">
        <view class="left">
          <view class="title">
            {{ batteryData.connected ? batteryData.protectBluetoothName : '--' }}
          </view>
          <view class="label">保护板蓝牙</view>
        </view>
        <view class="right">
          <image src="../../static/images/setting.png" mode=""></image>
        </view>
      </view>
      <view class="event-item" style="width: 146rpx" @click="handleUnProtect">
        <view style="width: 100%; text-align: center; font-size: 30rpx">保护板解绑</view>
      </view>
    </view>
    <DeviceList
      ref="deviceList"
      :cur-device-id="batteryData.deviceId ? batteryData.deviceId : ''"></DeviceList>
    <MySelect ref="MySelect" @confirm="selectConfirm"></MySelect>
    <MyInput ref="MyInput" @confirm="inputConfirm"></MyInput>
    <Ota ref="Ota"></Ota>
    <ProtectBluetooth
      ref="ProtectBluetooth"
      :device-list="protectDevices"
      :cur-mac="batteryData.protectBluetoothMac"
      @cancel="handleProtectCancel"
      @confirm="handleProtectConfirm"></ProtectBluetooth>
  </view>
</template>

<script>
import BluetoothManager from '@/utils/BluetoothManager'
const eventManager = require('@/utils/eventManager.js')
import DeviceList from '@/components/deviceMode/index.vue'
import MySelect from '@/components/mySelect/index.vue'
import MyInput from '@/components/myInput/index.vue'
import Ota from '@/components/ota/index.vue'
import ProtectBluetooth from '@/components/protectBluetooth/index.vue'
import { batteryTypeList } from '@/utils/coreData.js'
import { mapActions, mapGetters } from 'vuex'
var encoding = require('@/utils/encoding.js')
export default {
  components: {
    DeviceList,
    MySelect,
    MyInput,
    Ota,
    ProtectBluetooth,
  },
  data() {
    return {
      devices: [],
      protectDevices: [],
    }
  },
  onLoad() {
    uni.$on('syncBluetoothList', (res) => {
      this.syncBluetoothList(res)
    })
    BluetoothManager.initBluetooth()
    eventManager.addListener('notifyBLECharacteristicOk', (res) => {})
  },
  computed: {
    ...mapGetters({
      batteryData: 'battery/batteryData',
      vehicleTypeData: 'battery/vehicleTypeData',
      sourceData: 'battery/sourceData',
    }),
    sourceName() {
      console.log('获取数据name:', this.sourceData)
      const soucreItem = this.sourceData.find((item) => item.value === this.batteryData.curSourceId)
      return soucreItem ? soucreItem.label : ''
    },
  },

  methods: {
    ...mapActions({
      setBatteryData: 'battery/setBatteryData',
    }),
    async searchDevices() {
      this.$refs['deviceList'].show()
    },
    //车型 电池选择
    selectOpen(title) {
      if (!this.batteryData.connected) {
        console.error('未连接设备')
        return
      }
      let optionList = []
      let cmd = null
      let curVal = ''
      console.log(title)
      switch (title) {
        case '车型选择':
          cmd = 0x08
          optionList = this.vehicleTypeData
          curVal = this.batteryData.vehicleType
          break
        case '电池类型':
          cmd = 0x0e
          optionList = batteryTypeList
          curVal = this.batteryData.batteryType
          break
        case '数据源':
          cmd = 0x0b
          optionList = this.sourceData
          curVal = this.batteryData.curSourceId
          break
      }
      this.$refs['MySelect'].show({ title, optionList, curVal, cmd })
    },
    inputOpen(title) {
      if (!this.batteryData.connected) {
        console.error('未连接设备')
        return
      }
      let cmd = null
      let value = ''
      let inputType = 'text'
      switch (title) {
        case '蓝牙名称':
          cmd = 0x04
          inputType = 'text'
          value = this.batteryData.bluetoothName
          break
        case '续航校准':
          cmd = 0x0d
          inputType = 'number'
          break
        case '电池串数':
          cmd = 0x03
          inputType = 'number'
          break
        case '容量':
          cmd = 0x06
          inputType = 'number'
          break
        case '电耗':
          cmd = 0x07
          inputType = 'digit'
          break
      }
      this.$refs['MyInput'].show({ title, inputType, value, cmd })
    },
    //选择确认
    selectConfirm(cmd, val) {
      console.log(cmd, val)
      this.sendCommand(cmd, [Number(val)])
      if (cmd == 0x0b) {
        //没有通知直接手动更新
        let update = {
          curSourceId: Number(val),
        }
        this.setBatteryData(update)
      }
    },
    inputConfirm(cmd, val) {
      let sendVal
      switch (cmd) {
        case 0x04:
          let prefix = 'JJN-'
          if (!val.startsWith(prefix)) {
            // 如果不包含，则在前面拼接上该前缀
            val = prefix + val
          }
          const nameBytes = []

          for (let i = 0; i < val.length; i++) {
            nameBytes.push(val.charCodeAt(i))
          }
          sendVal = nameBytes
          break
        case 0x0d:
          var buffer = new ArrayBuffer(2)
          var view = new DataView(buffer)
          view.setUint16(0, Number(val))
          sendVal = [view.getUint8(0), view.getUint8(1)]
          break
        case 0x03:
        case 0x06:
          sendVal = [Number(val)]
          break
        case 0x07:
          var buffer = new ArrayBuffer(4)
          var view = new DataView(buffer)
          view.setFloat32(0, Number(val))
          sendVal = [view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3)]
          break
      }
      this.sendCommand(cmd, sendVal)
    },
    sendCommand(cmd, val) {
      BluetoothManager.sendCommand(
        this.batteryData.deviceId,
        this.batteryData.serviceId,
        this.batteryData.writeUuid,
        cmd,
        val
      )
    },
    startOat() {
      if (!this.batteryData.connected) {
        console.error('未连接设备')
        return
      }
      this.$refs['Ota'].startOta()
    },
    handleProtectBluetooth() {
      if (!this.batteryData.connected) {
        console.error('未连接设备')
        return
      }
      //发送查询命令
      this.sendCommand(0x18, [1])
      this.$refs['ProtectBluetooth'].show()
    },
    handleProtectConfirm(data) {
      let cmd = 0x0c
      let type = 0x01
      let macAddressNew = data.macAddress.replace(/:/g, '')
      if (macAddressNew.length !== 12) {
        console.error('无效的MAC地址')
        return
      }
      let send = [type]
      // 使用数组遍历
      var byteIndex = 0
      for (var i = 0; i < macAddressNew.length; i += 2) {
        var byte = parseInt(macAddressNew.substr(i, 2), 16)
        send.push(byte)
        byteIndex++
      }
      for (let i = 0; i < data.name.length; i++) {
        send.push(data.name.charCodeAt(i))
      }
      this.sendCommand(cmd, send)
      //手动更新
      let update = {
        protectBluetoothName: data.name,
        protectBluetoothMac: data.macAddress,
      }
      this.setBatteryData(update)
    },
    handleProtectCancel() {
      this.protectDevices = []
    },
    handleUnProtect() {
      uni.showModal({
        title: '提示',
        content: '确定解除当前保护板么?',
        success: (res) => {
          if (res.confirm) {
            this.sendCommand(0x0c, [0x00])
            let update = {
              protectBluetoothName: '',
              protectBluetoothMac: '',
            }
            this.setBatteryData(update)
          } else if (res.cancel) {
          }
        },
      })
    },
    syncBluetoothList(data) {
      //同步蓝牙列表
      let exit = this.protectDevices.some((item) => item.macAddress == data.macAddress)
      if (!exit) {
        this.protectDevices.push(data)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.index-content {
  padding-bottom: 200rpx;
  .logo {
    width: 100%;
    margin-top: 100rpx;
    text-align: center;
    image {
      width: 126rpx;
    }
  }
  .device-list {
    width: calc(100% - 65rpx);
    padding: 0 25rpx 0 40rpx;
    margin: 20rpx 0;
    .device-item {
      width: 100%;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      .item-left {
        display: flex;
        align-items: center;
        margin-right: 20rpx;
        .label {
          width: 185rpx;
          font-family: MicrosoftYaHei;
          font-size: 36rpx;
          color: #666666;
        }
        .content {
          width: 320rpx;
          font-family: MicrosoftYaHei;
          font-size: 44rpx;
          color: #574166;
          overflow: hidden;
          white-space: nowrap;
        }
      }
      .item-right {
        .item-btn {
          width: 158rpx;
          height: 55rpx;
          text-align: center;
          line-height: 55rpx;
          background-color: #574166;
          border-radius: 10rpx;
          font-family: MicrosoftYaHei;
          font-size: 36rpx;
          color: #fbfbfb;
        }
      }
    }
  }

  .wendu-box {
    padding: 0 25rpx 0 40rpx;
    display: flex;
    justify-content: flex-end;
    .device-wendu {
      width: 158rpx;
      font-family: MicrosoftYaHei;
      font-size: 27rpx;
      color: #574166;
      .icon image {
        width: 25rpx;
        height: 45rpx;
      }
    }
  }
  .device-rule-box {
    padding: 0 25rpx 0 40rpx;
    .device-rule-top {
      display: flex;
      justify-content: flex-end;

      image {
        width: 158rpx;
        height: 36rpx;
      }
    }
    .rule-item {
      display: flex;
      align-items: flex-end;
      margin-bottom: 30rpx;
      .item-master {
        flex: 1;
        .top {
          width: 100%;
          display: flex;
          .title {
            flex: 1;
            font-family: MicrosoftYaHei;
            font-size: 68rpx;
            color: #574166;
            display: flex;
            justify-content: center;
          }
        }
        .rule-img {
          image {
            width: 100%;
          }
        }
      }
      .item-btn {
        width: 221rpx;
        height: 76rpx;
        background: #574166;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        font-family: MicrosoftYaHei;
        font-size: 51rpx;
        color: #fbfbfb;
        text-align: center;
        line-height: 76rpx;
        margin-left: 36rpx;
      }
    }
  }

  .device-event {
    width: calc(100% - 65rpx);
    padding: 0 25rpx 0 40rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .event-item {
      display: flex;
      padding: 10rpx 18rpx;
      margin-bottom: 20rpx;
      justify-content: space-between;
      align-items: center;
      background: #e3cef5;
      border-radius: 6rpx 6rpx 6rpx 6rpx;

      .left {
        width: calc(100% - 70rpx);
        overflow: hidden;
        white-space: nowrap;
        .title {
          font-family: MicrosoftYaHei;
          font-size: 50rpx;
          height: 70rpx;
          color: #3a2b44;
        }
        .label {
          font-family: MicrosoftYaHei;
          font-size: 23rpx;
          color: #3a2b44;
        }
      }
      .right {
        width: 58rpx;
        image {
          width: 58rpx;
          height: 58rpx;
        }
      }
    }
  }
}
</style>
